import { defineStore } from 'pinia'
import request from '@/utils/request'
import {getToken, removeToken, setToken} from "@/utils/auth";  // 注意：使用封装后的 axios

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: getToken() || '',
    user: null,
    roles: []
  }),

  actions: {
    async login(loginParams) {
      try {
        const res = await request.post('/v1/auth/login', loginParams)
        if (res.code !== 0) {
          console.error('Login failed:', res.message)
          return false
        }
        const token  = res.data.token
        this.token = token
        setToken(token)
        // console.log(getToken())
        return true
      } catch (err) {
        console.error('请求异常:', err)
        return false
      }
    },

    async getNewToken() {
      if (!this.token) return false
      try {
        const res = await request.post('/v1/auth/refresh-token', null, {
          headers: {
            'Authorization': `Bearer ${this.token}`
          }
        })
        if (res.code === 0 && res.data.token) {
          this.token = res.data.token
          setToken(res.data.token)
          return true
        } else {
          this.logout()
          return false
        }
      } catch (err) {
        console.error('刷新 token 失败:', err)
        this.logout()
        return false
      }
    },

    async fetchRoles() {
      try {
        const res = await request.get('/roles')
        this.roles = res
      } catch (err) {
        console.error('Failed to fetch roles:', err)
      }
    },

    logout() {
      this.token = ''
      this.user = null
      this.roles = []
      removeToken()
    }
  }
})